import { Component, OnInit } from '@angular/core';
import { UserService } from '../service/user.service';
import { Message } from 'primeng/components/common/api';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  msgs: Message[] = [];
  constructor(public userService: UserService, public http: HttpClient, public router: Router) {
  }

  ngOnInit() {
    this.http.get('/user').subscribe(result => {
      if (result['error'] === '未登录') {
        this.router.navigateByUrl('/user/login');
      } else {
        this.userService.currentUser = result['data'];
      }
    });
  }

  onSubmit() {
    if (this.userService.currentUser.nickname === ''
        ||  this.userService.currentUser.email === '' ||
            this.userService.currentUser.password === '') {
      this.msgs = [];
      this.msgs.push({ severity: 'error', summary: '邮箱,昵称,密码,任何一个都不能为空' });
      return;
    }
    this.http.post('/user', this.userService.currentUser).subscribe(result => {
      if (result['error'] === '') {
        this.msgs = [];
        this.msgs.push({ severity: 'info', summary: '保存成功' });
        this.ngOnInit();
        return;
      }
      if (result['error'] === '未登录') {
        this.userService.currentUser = null;
        this.router.navigateByUrl('/user/login');
        return;
      }
      if (result['error']) {
        this.msgs = [];
        this.msgs.push({ severity: 'info', summary: result['error'] });
      }

    });

  }

}
